<!-- brand component -->
<template>
  <div>
    <v-card>
      <v-card-title>
        <v-btn small raised color="primary" @click="showAddedBrandDialog">新增品牌</v-btn>
        <v-spacer></v-spacer>
        <v-text-field
          v-model="search"
          append-icon="search"
          label="Search"
          single-line
          hide-details
          @keyup.enter="searchChanged"
          @click:append="searchChanged"
        ></v-text-field>
      </v-card-title>
      <v-data-table
        :headers="headers"
        :items="brandList"
        :options.sync="options"
        :server-items-length="total"
        :loading="loading"
        class="elevation-1"
        @update:options="optionsChanged"
      >
        <template v-slot:item.image="{ item }">
          <img :src="item.image" width="100" />
        </template>
        <template v-slot:item.option="{ item }">
          <v-icon small class="mr-2" @click="editBrand(item)">edit</v-icon>
          <v-icon small @click="deleteBrand(item)">delete</v-icon>
        </template>
      </v-data-table>
    </v-card>
    <!-- 添加品牌对话框 -->
    <v-dialog v-model="dialog" max-width="500px">
      <v-card>
        <v-toolbar color="primary" :dark="true">
          <v-toolbar-title>{{ dialogTitle }}</v-toolbar-title>
        </v-toolbar>
        <v-stepper v-model="e1">
          <v-stepper-header>
            <v-stepper-step :complete="e1 > 1" step="1">基础信息</v-stepper-step>

            <v-divider></v-divider>

            <v-stepper-step step="2">品牌LOGO</v-stepper-step>
          </v-stepper-header>

          <v-stepper-items>
            <v-stepper-content step="1">
              <v-card class="mb-12" color="grey lighten-5" height="300px">
                <v-form ref="addBrandFormRef" v-model="valid">
                  <v-text-field v-model="brandName" :rules="nameRules" label="品牌名称" required></v-text-field>
                  <v-text-field v-model="initial" :rules="initialRules" label="首字母" required></v-text-field>
                  <v-cascader
                    v-model="categories"
                    label="品牌分类"
                    url="/item/category/list"
                    multiple
                    required
                  />
                </v-form>
              </v-card>
              <v-btn color="primary" @click="e1 = 2">Continue</v-btn>
              <v-spacer></v-spacer>
            </v-stepper-content>

            <v-stepper-content step="2">
              <v-card class="mb-12" color="grey lighten-5" height="300px">
                <v-layout column>
                  <v-flex xs3>
                    <span style="font-size: 16px; color: #444">品牌LOGO：</span>
                  </v-flex>
                  <v-flex>
                    <v-upload
                      v-model="image"
                      url="/upload/image"
                      :multiple="false"
                      :pic-width="250"
                      :pic-height="90"
                    />
                  </v-flex>
                </v-layout>
              </v-card>
              <v-row>
                <v-btn color="primary" @click="e1 = 1">Continue</v-btn>
                <v-spacer></v-spacer>
                <v-btn color="grey lighten-1" @click="closeAddBrandDialog">取消</v-btn>
                <v-btn color="grey lighten-2" @click="resetAddBrandForm">重置</v-btn>
                <v-btn color="primary" @click="submitAddBrandForm">确认</v-btn>
              </v-row>
            </v-stepper-content>
          </v-stepper-items>
        </v-stepper>
      </v-card>
    </v-dialog>
    <!-- 修改品牌对话框 -->
    <v-dialog v-model="editedBrandFormDialog" max-width="500px">
      <v-card>
        <v-toolbar color="primary" :dark="true">
          <v-toolbar-title>{{ dialogTitle }}</v-toolbar-title>
        </v-toolbar>
        <v-stepper v-model="e1">
          <v-stepper-header>
            <v-stepper-step :complete="e1 > 1" step="1">基础信息</v-stepper-step>

            <v-divider></v-divider>

            <v-stepper-step step="2">品牌LOGO</v-stepper-step>
          </v-stepper-header>

          <v-stepper-items>
            <v-stepper-content step="1">
              <v-card class="mb-12" color="grey lighten-5" height="300px">
                <v-form ref="editedBrandFormRef" v-model="valid">
                  <v-text-field
                    v-model="editedBrandForm.name"
                    :rules="nameRules"
                    label="品牌名称"
                    required
                  ></v-text-field>
                  <v-text-field
                    v-model="editedBrandForm.initial"
                    :rules="initialRules"
                    label="首字母"
                    required
                  ></v-text-field>
                  <v-cascader
                    v-model="editedCategores"
                    label="品牌分类"
                    url="/item/category/list"
                    multiple
                    required
                  />
                </v-form>
              </v-card>
              <v-btn color="primary" @click="e1 = 2">Continue</v-btn>
              <v-spacer></v-spacer>
            </v-stepper-content>

            <v-stepper-content step="2">
              <v-card class="mb-12" color="grey lighten-5" height="300px">
                <v-layout column>
                  <v-flex xs3>
                    <span style="font-size: 16px; color: #444">品牌LOGO：</span>
                  </v-flex>
                  <v-flex>
                    <v-upload
                      v-model="editedBrandForm.image"
                      url="/upload/image"
                      :multiple="false"
                      :pic-width="250"
                      :pic-height="90"
                    />
                  </v-flex>
                </v-layout>
              </v-card>
              <v-row>
                <v-btn color="primary" @click="e1 = 1">Continue</v-btn>
                <v-spacer></v-spacer>
                <v-btn color="grey lighten-1" @click="closeEditBrandDialog">取消</v-btn>
                <v-btn color="grey lighten-2" @click="resetEditBrandForm">重置</v-btn>
                <v-btn color="primary" @click="submitEditBrandForm">确认</v-btn>
              </v-row>
            </v-stepper-content>
          </v-stepper-items>
        </v-stepper>
      </v-card>
    </v-dialog>
  </div>
</template>

<script>
export default {
  data: () => ({
    search: "", // 搜索关键字
    // v-data-table 配置项
    options: {
      page: 1,
      itemsPerPage: 10,
      sortBy: ["id"],
      sortDesc: [true]
    },
    total: 0, // 总条目数
    pageCount: 1, // 总页数
    brandList: [], // 当前页品牌数据列表
    loading: false, // 表格数据加载条
    // 表格头信息
    headers: [
      { text: "ID", value: "id" },
      { text: "名称", value: "name", sortable: false },
      { text: "Logo", value: "image", sortable: false },
      { text: "首字母", value: "initial" },
      { text: "操作", value: "option", sortable: false }
    ],
    dialog: false, // 对话框显示与隐藏标志
    editedFlag: false, // 对话框标题添加与修改标志
    e1: 1, // 步骤条
    valid: false, // 表单校验结果标志
    brandName: "", // 品牌名称
    // 品牌名称校验规则
    nameRules: [
      v => !!v || "Name is required",
      v => (v && v.length >= 1) || "Name must be greater than 1 characters"
    ],
    initial: "", // 品牌首字母
    // 品牌首字母校验规则
    initialRules: [
      v => !!v || "Initial  is required",
      v => /^[A-Z]$/.test(v) || "Initial must be a capital letter"
    ],
    image: "", // LOGO
    categories: [], // 级联分类信息
    // 被修改的品牌表单对象
    editedBrandForm: {
      id: 0,
      name: "",
      initial: "",
      image: ""
    },
    editedBrandFormDialog: false, // 是否显示修改品牌表单对话框
    editedCategores: [] //修改品牌分类列表
  }),

  created() {
    this.getBrandList();
  },
  beforeUpdate() {
    // console.log(this.editedCategores);
  },
  computed: {
    dialogTitle() {
      return this.editedFlag ? "修改品牌" : "添加新品牌";
    }
  },
  methods: {
    // 获取分页搜索品牌列表
    getBrandList() {
      this.axios
        .get("/item/brand/page", {
          params: {
            search: this.search,
            page: this.options.page,
            rows: this.options.itemsPerPage,
            sortBy: this.options.sortBy.join(","),
            sortDesc: this.options.sortDesc.join(",")
          }
        })
        .then(resp => {
          // console.log(resp);
          if (resp.status != 200) {
            // 报错提示
          }
          this.brandList = resp.data.items;
          // console.log(this.brandList);
          this.total = resp.data.total;
          this.options.pageStop = resp.data.totalPage;
        });
    },
    // 编辑品牌
    editBrand(item) {
      console.log(item.id);
      // 显示修改品牌对话框
      this.editedBrandFormDialog = true;
      // 1、初始化被修改品牌表单对象
      this.editedBrandForm.id = item.id;
      this.editedBrandForm.name = item.name;
      this.editedBrandForm.initial = item.initial;
      this.editedBrandForm.image = item.image;
      // console.log(this.editedBrandForm);
      // 2、初始化品牌分类
      this.getCategoriesByBid(item.id);
      // 3、初始化标题
      this.editedFlag = true;
    },
    // 根据品牌ID获取分类
    getCategoriesByBid(bid) {
      this.axios.get(`/item/brand/categories/${bid}`).then(resp => {
        if (resp.status != 200) {
          // 报错提示
          this.$message.error("根据品牌ID查询分类信息出错");
        }
        // 获取成功
        // console.log(resp.data);
        // 初始化分类信息
        this.editedCategores = resp.data;
      });
    },
    // 关闭修改品牌对话框
    closeEditBrandDialog() {
      this.$refs.editedBrandFormRef.reset();
      this.editedCategores = [];
      this.e1 = 1;
      this.editedBrandFormDialog = false;
    },
    // 重置修改品牌表单
    resetEditBrandForm() {
      this.$refs.editedBrandFormRef.reset();
      this.editedCategores = [];
    },
    // 提交修改品牌表单
    submitEditBrandForm() {
      // console.log(this.editedBrandForm);
      const param = {
        brand: this.editedBrandForm,
        categories: this.editedCategores.map(o => o.id)
      };
      console.log(param);
      this.axios.put("/item/brand/editBrand", param).then(resp => {
        if (resp.status != 200) {
          this.$message.error("修改品牌失败");
        }
        // console.log(resp.data);
        this.getBrandList();
        this.closeEditBrandDialog();
      });
    },
    // 删除指定品牌
    deleteBrand(item) {
      // console.log(item);
      // return
      // 删除确认
      this.$message
        .confirm("此操作将会永久删除该商品，确定要删除吗")
        .then(() => {
          // 确认删除，执行删除操作
          this.axios
            .delete('item/brand', {
              params: {
                bid: item.id,
                image: item.image
              }
            })
            .then(resp => {
              // console.log(resp)
              if (resp.status !== 204) {
                return this.$message.error("删除商品失败");
              }
              // 成功删除，重新获取数据
              this.getBrandList();
            });
        })
        .catch(() => {
          // 取消删除
          this.$message.info("已取消删除");
        });
    },
    searchChanged() {
      if (this.search !== "") {
        // console.log(this.search);
        this.getBrandList();
      }
    },
    // 分组、排序项改变，重新向后端请求数据
    optionsChanged() {
      // console.log(this.options);
      this.getBrandList();
    },
    // 显示添加品牌对话框
    showAddedBrandDialog() {
      // 1、初始化对话框标题
      this.editedFlag = false;
      // 2、显示对话框
      this.dialog = true;
    },
    // 重置添加品牌表单
    resetAddBrandForm() {
      // 情况输入框内容
      this.$refs.addBrandFormRef.reset();
      // 手动情况商品分类
      this.categories = [];
    },
    // 关闭添加品牌对话框
    closeAddBrandDialog() {
      this.e1 = 1;
      this.dialog = false;
    },
    // 提交添加品牌表单
    submitAddBrandForm() {
      // 校验
      if (!this.$refs.addBrandFormRef.validate()) {
        this.$message.eror("填写内容不符合要求");
      }
      // 发送添加请求
      // console.log(this.categories);
      // 1、品牌参数
      const param = {
        name: this.brandName,
        initial: this.initial,
        image: this.image
      };
      // 2、分类ID cids
      param.cids = this.categories.map(c => c.id).join(",");
      // 3、发送后端
      // console.log(param);
      this.axios.post("item/brand", param).then(resp => {
        if (resp.status != 201) {
          this.$message.error("添加品牌失败");
        }
        // console.log(resp);
        // 添加成功
        // 1、清空表单
        this.resetAddBrandForm();
        // 2、关闭对话框
        this.closeAddBrandDialog();
        // 3、重新请求品牌列表
        this.getBrandList();
      });
    }
  },

  components: {}
};
</script>

<style lang='scss' scoped>
</style>